package org.yystory.ui;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yystory.dataobject.StoryObject;
import org.yystory.entity.Story;
import org.yystory.service.StoryService;
import org.yystory.utility.ErrorParser;

import com.alibaba.fastjson.JSON;

public class RandomStoryServlet extends HttpServlet {

	private static final long serialVersionUID = 7549448652031185434L;

	public RandomStoryServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	private void response(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			Story story = StoryService.random();
			StoryObject object = new StoryObject();
			object.setName(story.getName());
			object.setStoryId(story.getId());
			object.setUserId(story.getUserId());
			object.setDate(story.getDate());
			response.getWriter().print(JSON.toJSONString(object));
			response.getWriter().close();
		} catch (Exception e) {
			response.getWriter().print(
					ErrorParser.parseError("RandomStoryServlet", e.getClass()
							.getName() + ":" + e.getMessage()));
			response.getWriter().close();
		}
	}

}
